package com.mg.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mg.common.vo.ResponseResult;
import com.mg.common.vo.ResponseStatus;
import com.mg.message.common.SelectByTimeUtils;
import com.mg.message.dto.ResponMessageOrder;
import com.mg.message.entity.User;
import com.mg.message.mapper.MessageOrderMapper;
import com.mg.message.mapper.UserMapper;
import com.mg.message.service.UserService;
import com.mg.message.vo.RequestSelectUser;
import com.mg.message.dto.ResponUser;
import com.mg.message.vo.UsersResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    MessageOrderMapper messageOrderMapper;

    @Override
    @Transactional
    public ResponseResult<UsersResponse> getUsersByConditions(RequestSelectUser requestSelectUser) {
        ResponseResult<UsersResponse> entity = null;

        try {
            /**
             * 功能：群发，选择需要发送的人群
             * 业务逻辑：
             * 1、添加用户创建时间条件限制，状态0表示没有限制，当有自定义时间范围时，优先以自定义时间范围查询
             * 2、添加订单消费时间条件限制（查询出时间范围内的订单对应的用户，以及每个用户的订单数），状态0表示没有限制，当有自定义时间范围时，优先以自定义时间范围查询
             * 3、添加消费次数条件限制（查询出满足消费次数条件的用户），状态0表示没有限制，优先以自定义次数范围查询
             * 4、最后，条件2和条件3确定的用户群，与条件1的用户群的交集
             */
            /**
             * 补充：
             * 功能：指定手机号发送短信，可以指定多个手机号（以 ";" 符隔开）
             * 业务逻辑：
             * 1、在前端实现没指定一个手机号，就重新统计用户个数，并计算出短信总费用。
             * 2、在前端得出的总费用（除群发），用于【新建短信】和【修改短信】时，给后台传输总费用字段，添加至短信主表
             */
            List<User> users = new ArrayList<>();
            //1、用户创建时间条件限制查询
            if (StringUtils.isEmpty(requestSelectUser.getUserCreateStartTime()) || StringUtils.isEmpty(requestSelectUser.getUserCreateEndTime())) {
                if (!StringUtils.isEmpty(requestSelectUser.getTimeLimit())) {
                    if (requestSelectUser.getTimeLimit().equals(0)) {
                        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                        userQueryWrapper.select(User.COL_ID, User.COL_PHONE);
                        users = userMapper.selectList(userQueryWrapper);
                    } else {
                        Integer timeLimit = requestSelectUser.getTimeLimit();

                        //线程安全的时间工具
                        List<String> beginAndEndTime = SelectByTimeUtils.getBeginAndEndTime(timeLimit);
                        String startTime = beginAndEndTime.get(0);
                        String endTime = beginAndEndTime.get(1);

                        users = userMapper.selectUserByTimeLimit(startTime, endTime);
                    }
                } else {
                    return ResponseResult.error(ResponseStatus.FAIL);
                }
            } else {
                String userCreateStartTime = requestSelectUser.getUserCreateStartTime();
                String userCreateEndTime = requestSelectUser.getUserCreateEndTime();
                users = userMapper.selectUserByTimeLimit(userCreateStartTime, userCreateEndTime);
            }

            //2、消费时间条件限制查询
            List<ResponMessageOrder> responMessageOrders = new ArrayList<>();
            if (StringUtils.isEmpty(requestSelectUser.getTradeStartTime()) || StringUtils.isEmpty(requestSelectUser.getTradeEndTime())) {
                if (!StringUtils.isEmpty(requestSelectUser.getTradeLimit())) {
                    if (requestSelectUser.getTradeLimit().equals(0)) {
                        //不限制查询（状态为0）
                        responMessageOrders = messageOrderMapper.selectOrderCount();
                    } else {
                        //选择查询
                        Integer tradeLimit = requestSelectUser.getTradeLimit();

                        //线程安全的时间工具
                        List<String> beginAndEndTime = SelectByTimeUtils.getBeginAndEndTime(tradeLimit);
                        String startTime = beginAndEndTime.get(0);
                        String endTime = beginAndEndTime.get(1);

                        responMessageOrders = messageOrderMapper.selectOrderCountWithLimit(startTime, endTime);
                    }
                } else {
                    return ResponseResult.error(ResponseStatus.FAIL);
                }
            } else {
                String tradeStartTime = requestSelectUser.getTradeStartTime();
                String tradeEndTime = requestSelectUser.getTradeEndTime();
                responMessageOrders = messageOrderMapper.selectOrderCountWithLimit(tradeStartTime, tradeEndTime);
            }

            //3、消费次数条件限制
            List<ResponMessageOrder> responMessageOrdersLimitCount = new ArrayList<>();
            if (StringUtils.isEmpty(requestSelectUser.getBeginCount()) || StringUtils.isEmpty(requestSelectUser.getEndCount())) {
                if (!StringUtils.isEmpty(requestSelectUser.getCountLimit())) {
                    if (requestSelectUser.getCountLimit().equals(0)) {
                        responMessageOrdersLimitCount = responMessageOrders;
                    } else {
                        Integer countLimit = requestSelectUser.getCountLimit();

                        if (responMessageOrders != null) {
                            responMessageOrders.stream().filter((ResponMessageOrder responMessageOrder) -> {
                                Integer count = responMessageOrder.getCount();
                                if (count >= countLimit) {
                                    return true;
                                }
                                return false;
                            }).forEach(responMessageOrdersLimitCount::add);
                        }
                    }
                } else {
                    return ResponseResult.error(ResponseStatus.FAIL);
                }
            } else {
                Integer beginCount = requestSelectUser.getBeginCount();
                Integer endCount = requestSelectUser.getEndCount();

                if (responMessageOrders != null) {
                    responMessageOrders.stream().filter((ResponMessageOrder responMessageOrder) -> {
                        Integer count = responMessageOrder.getCount();
                        if (count >= beginCount && count <= endCount) {
                            return true;
                        }
                        return false;
                    }).forEach(responMessageOrdersLimitCount::add);
                }

            }

            //【双循环待优化】
            List<ResponUser> responUsers = new ArrayList<>();
            for (ResponMessageOrder responMessageOrder : responMessageOrdersLimitCount) {
                Integer userId = responMessageOrder.getUserId();
                for (User user : users) {
                    Integer id = user.getId();
                    if (userId.equals(id)) {
                        ResponUser responUser = new ResponUser();
                        BeanUtils.copyProperties(user, responUser);
                        responUsers.add(responUser);
                    }
                }
            }

            //处理返回值
            UsersResponse usersResponse = new UsersResponse();
            int size = responUsers.size();
            usersResponse.setTotalCount(size);
            usersResponse.setResponUsers(responUsers);
            //计算总价格
            BigDecimal bd1 = new BigDecimal(UsersResponse.PER_MESSAGE);
            BigDecimal bd2 = new BigDecimal(size);
            BigDecimal result = bd2.multiply(bd1);
            String reStr = result.toString();
            double totalPrice = Double.parseDouble(reStr);
            usersResponse.setTotalPay(totalPrice);

            entity = ResponseResult.ok(usersResponse);

        } catch (Exception e) {
            return ResponseResult.error(ResponseStatus.FAIL);
        }

        return entity;
    }
}
